# 接口父类
import os.path

import jmespath
from loguru import logger
import requests
import yaml

from base.basic import HOST, TOKEN

logger.add('logs/20251121.log')
class Api:
    def __init__(self,method,path,params=None,headers=None,json=None):
        """
        :param method: 请求的方法
        :param url: 接口地址
        :param headers: 请求头
        :param json: 请求体
        """
        self.method = method
        self.url = f'{HOST}{path}'
        self.params = params
        #公共头信息
        self.pub_headers = {
            'Content-Type':"application/json;charset=UTF-8",
            'Authori-zation':f'Bearer {TOKEN}'
        }
        if headers is None:
            self.headers = self.pub_headers
        else:
            self.headers = {**self.pub_headers,**headers}

        self.json = json
        logger.info(f'准备发送接口{self.url},接口的请求头{self.headers},请求体{self.json}')


        #发送请求获取响应
        self.response = requests.request(self.method,
                                         self.url,
                                         params=self.params,
                                         headers=self.headers,
                                         json=self.json)
        logger.info(f'接收响应{self.response.status_code},响应的头{self.response.headers},体{self.response.text}')
    def assert_Resp(self,status_code,*values):
        assert status_code == self.response.status_code
        for value in values:
            assert value in self.response.text
    def get_value(self,jsonpath):
        return jmespath.search(jsonpath,self.response.json())

    def save_yaml(self,jsonpath,filename):
        """
        :param jsonpath: 输入要求从响应中提取的文本的json路径，不能从$开始写
        :param filename: 提取的数据要写入的文件
        :return:
        """
        #取值
        msg = self.get_value(jsonpath)
        #保存
        filepath = os.path.join(os.path.dirname(__file__),'../config',filename)
        with open(filepath,'w',encoding='utf-8') as f:
            yaml.dump(msg,f,explicit_end=False, allow_unicode=True)

